using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.OnScreen;
using UnityEngine.UIElements;

namespace BlockOS.Client.GUI
{
    public class OnScreenArea : OnScreenControl, IPointerDownHandler, IPointerUpHandler, IPointerMoveHandler
    {
        [SerializeField]
        private float m_TimeDeadZone = 0.1f;

        [InputControl(layout = "Vector2", processors = "")]
        [SerializeField]
        private string m_ControlPath;
        protected override string controlPathInternal { get => m_ControlPath; set => m_ControlPath = value; }

        private int m_FingerId;

        private float timer = 0;
        private bool isDown;
        private Vector2 prevPosition;
        private Vector2? delta;

        private bool isDeltaSent = true;

        private void Update()
        {
            if (isDown)
            {
                if (timer >= m_TimeDeadZone)
                {
                    if (delta != null)
                    {
                        SendValueToControl(delta.Value);
                        delta = null;
                        isDeltaSent = true;
                    }
                    else if(isDeltaSent)
                    {
                        SendValueToControl(Vector2.zero);
                        isDeltaSent = false;
                    }
                }
                timer += Time.deltaTime;
            }
        }
        public void OnPointerDown(PointerEventData eventData)
        {
            prevPosition = eventData.position;
            m_FingerId = eventData.pointerId;
            isDown = true;
            timer = 0;
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            SendValueToControl(Vector2.zero);
            isDown = false;
        }

        public void OnPointerMove(PointerEventData eventData)
        {
            if (eventData.pointerId == m_FingerId)
            {
                delta = eventData.position - prevPosition;
                prevPosition = eventData.position;
            }
        }
    }
}
